package com.taxicall.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import com.taxicall.entities.NetworkMessage;
import com.taxicall.udptransport.SerializationUtils;
import com.taxicall.udptransport.UdpNetworkService;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

public class UDPService extends IntentService {
	
	public UDPService() throws IOException {
		super("UDPService");
		System.out.println("Service constructor");
	}
	public final static int PORT = 4000;
	public final static int BUFFER_SIZE = 4096;
	public static InetAddress serverip;
	

	private UdpNetworkService netService;
	private ResultReceiver resReceiver;
	private NetworkMessage msgToSend;
	private DatagramPacket packet;
	private NetworkMessage msg;
	private Bundle bundle;
	private InetAddress address;
	
	public NetworkMessage returnResults() {
		NetworkMessage msg = null;
		return msg;
	}
	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			netService = new UdpNetworkService(PORT, BUFFER_SIZE);
			System.out.println("Received intent");
		} catch (IOException e) {
			e.printStackTrace();
		}
		Object ob = intent.getExtras().get("resultReceiver");
		resReceiver = (ResultReceiver) ob;//intent.getExtras().get("resultReceiver");
		msgToSend = (NetworkMessage) intent.getSerializableExtra("msg");
		
		switch(msgToSend.getType()) {
			case GetStartLocations:
			case GetAllTaxis:
			try {
				address = InetAddress.getByName(intent.getExtras().getString("serverip"));
			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			}
				break;
			case RequestRide: 
				address = (InetAddress) intent.getSerializableExtra("ip");
				break;
		}
		try {
			netService.send(msgToSend, address, PORT);
			System.out.println("message sent\nwaiting for response");
			packet = netService.receive(6000);
			System.out.println("received response");
			bundle = new Bundle();
			
			if(packet != null) {
				msg = (NetworkMessage) SerializationUtils.deserialize(packet.getData());
				bundle.putSerializable("receivedMsg", msg);
				if(msg.getType() == NetworkMessage.MessageType.SetStartLocations) {
					resReceiver.send(MyResultReceiver.TAXI_LOCATIONS_RESULTS, bundle);
				}
				else if(msg.getType() == NetworkMessage.MessageType.SetAllTaxis) {
					resReceiver.send(MyResultReceiver.TAXI_RESULTS, bundle);
				}
				else if(msg.getType() == NetworkMessage.MessageType.RideReply) {
					resReceiver.send(MyResultReceiver.RIDE_REPLY, bundle);
				}
			}
			else {
				resReceiver.send(MyResultReceiver.TIMEOUT_REACHED, bundle);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			stopSelf();
		}
	}
}
